"use client";
import React, { useEffect, useState } from "react";
import { QRCode, Space } from "antd";
import axios from "axios";
import {
  Table,
  Image,
  TableHeader,
  TableColumn,
  TableBody,
  TableRow,
  TableCell,
  Input,
  Button,
  DropdownTrigger,
  Dropdown,
  DropdownMenu,
  DropdownItem,
  Chip,
  useDisclosure,
  Textarea,
  Modal,
  ModalContent,
  Spacer,
  ModalHeader,
  ModalFooter,
  ModalBody,
  Select,
  SelectItem,
  User,
  Pagination,
} from "@nextui-org/react";
import { DateInput } from "@nextui-org/date-input";
import {
  CalendarDate,
  parseDate,
  parseZonedDateTime,
  parseAbsoluteToLocal,
} from "@internationalized/date";
import { PlusIcon } from "./PlusIcon";
import { VerticalDotsIcon } from "./VerticalDotsIcon";
import { SearchIcon } from "./SearchIcon";
import { ChevronDownIcon } from "./ChevronDownIcon";
import { columns, users, statusOptions, statusList } from "./data";
import { capitalize } from "./utils";
import { CldUploadButton } from "next-cloudinary";
import { FileUp, Send } from "lucide-react";
import { useAuth, useUser } from "@clerk/nextjs";
import { ToastContainer, toast } from "react-toastify";
import { Note } from "@/util/type";
import moment from "moment";
import { cloneDeep } from "lodash";
import "react-toastify/dist/ReactToastify.css";
import "./contact.css";
import { log } from "console";
const statusColorMap = {
  active: "success",
  paused: "danger",
};

const INITIAL_VISIBLE_COLUMNS = ["title", "content", "status", "actions"];

export default function Contact() {
  const { userId } = useAuth();
  const [text, setText] = React.useState("https://gitee.com/liao-ziqiao");
  const [giteeUrl, setGiteeUrl] = useState<string>("");
  const [title, setTitle] = useState<string>("请输入日志名称！");
  const titleIsInvalid = React.useMemo(() => {
    if (title === "") {
      return true;
    } else {
      return false;
    }
  }, [title]);
  const giteeUrlIsInvalid = React.useMemo(() => {
    if (giteeUrl === "") {
      return true;
    } else {
      return false;
    }
  }, [giteeUrl]);
  const [status, setStatus] = useState<string>("");
  const handleStatusChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setStatus(e.target.value);
  };
  const [images, setImages] = useState<string[]>([]);

  const [date, setSelectedDate] = React.useState(
    parseAbsoluteToLocal("2024-05-17T07:45:00Z")
  );
  const [content, setContent] = useState<string>("请填写日志基本内容");
  const [avatar, setAvatar] = useState<string>("请填写头像地址链接");
  const [id, setId] = useState<string>("");
  const contentIsInvalid = React.useMemo(() => {
    if (content === "") {
      return true;
    } else {
      return false;
    }
  }, [content]);
  const [initData, setInitData] = React.useState<
    {
      userId: string;
      title: string;
      avatar: string;
      content: string;
      date: string;
      images: string[];
      status: string;
      giteeUrl: string;
    }[]
  >([]);
  const fetchTicketTopics = async () => {
    console.log("页面被调用");

    try {
      const response = await axios.get<{ notes: Note[] }>(
        process.env.API_ADDRESS + `/note?userId=${userId}`
      );
      console.log("获取到的数据", response);
      // setTopics(response.data.topics);
      if (response.data?.notes) {
        const { notes } = response.data;
        setInitData(notes);
      } else {
        setInitData(users);
      }
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };
  useEffect(() => {
    // let newUsers = cloneDeep(users);
    // setInitData(newUsers);
    fetchTicketTopics();
  }, []); // 仅在组件挂载时执行
  useEffect(() => {
    // 这个代码块会在images状态发生变化后执行
    console.log(images); // 这里将是最新的images数组
  }, [images]); // 依赖项数组包含images，当images变化时触发effect
  const { isOpen, onOpen, onOpenChange } = useDisclosure();
  const [filterValue, setFilterValue] = React.useState("");
  const [modaltype, setModaltype] = React.useState("add");
  const [selectedKeys, setSelectedKeys] = React.useState(new Set([]));
  const [visibleColumns, setVisibleColumns] = React.useState(
    new Set(INITIAL_VISIBLE_COLUMNS)
  );
  const [statusFilter, setStatusFilter] = React.useState("all");
  const [rowsPerPage, setRowsPerPage] = React.useState(5);
  const [sortDescriptor, setSortDescriptor] = React.useState({
    column: "giteeUrl",
    direction: "ascending",
  });
  const [page, setPage] = React.useState(1);

  const pages = Math.ceil(initData.length / rowsPerPage);

  const hasSearchFilter = Boolean(filterValue);

  const headerColumns = React.useMemo(() => {
    if (visibleColumns === "all") return columns;

    return columns.filter((column) =>
      Array.from(visibleColumns).includes(column.uid)
    );
  }, [visibleColumns]);

  const filteredItems = React.useMemo(() => {
    let filteredUsers = [...initData];

    if (hasSearchFilter) {
      filteredUsers = filteredUsers.filter((user) =>
        user.title.toLowerCase().includes(filterValue.toLowerCase())
      );
    }
    if (
      statusFilter !== "all" &&
      Array.from(statusFilter).length !== statusOptions.length
    ) {
      filteredUsers = filteredUsers.filter((user) =>
        Array.from(statusFilter).includes(user.status)
      );
    }

    return filteredUsers;
  }, [initData, filterValue, statusFilter]);

  const items = React.useMemo(() => {
    const start = (page - 1) * rowsPerPage;
    const end = start + rowsPerPage;

    return filteredItems.slice(start, end);
  }, [page, filteredItems, rowsPerPage]);
  interface Item {
    id: number;
    title: string;
    content: string;
    date: string;
    status: string;
    avatar: string;
    giteeUrl: string;
  }
  // 假设我们有一个Modal组件来预览图片
  interface ImagePreviewModalProps {
    isOpen: boolean;
    onClose: () => void;
    image: string;
  }

  const ImagePreviewModal = ({
    isOpen,
    onClose,
    image,
  }: ImagePreviewModalProps) => {
    if (!isOpen) return null;

    return (
      <Modal onClose={onClose} isOpen={isOpen} size="4xl">
        <ModalContent>
          <ModalHeader>图片预览</ModalHeader>
          <ModalBody>
            <Image
              isZoomed
              alt="Card image"
              className="l-5"
              src={image}
              width="200%" // 使用百分比来适应Modal的大小
            />
          </ModalBody>
          <ModalFooter>
            <Button onClick={onClose} color="secondary" variant="light">
              关闭
            </Button>
          </ModalFooter>
        </ModalContent>
      </Modal>
    );
  };
  interface ImageComponentProps {
    image: string | "";
    images: string[];
    onRemoveImage: (image: string) => void; // 传入一个用于删除图片的函数
  }
  const ImageComponent: React.FC<ImageComponentProps> = ({
    image,
    images,
    onRemoveImage,
  }) => {
    const [previewIsOpen, setPreviewIsOpen] = useState<boolean>(false);
    const [isDeleteModalOpen, setIsDeleteModalOpen] = useState<boolean>(false);
    const handlePreview = () => {
      setPreviewIsOpen(true);
    };

    const handleClosePreview = () => {
      setPreviewIsOpen(false);
    };

    const handleDelete = () => {
      setIsDeleteModalOpen(true);
    };

    const handleDeleteConfirm = () => {
      setIsDeleteModalOpen(false);
      onRemoveImage(image); // 调用传入的删除图片函数
    };

    const handleDeleteCancel = () => {
      setIsDeleteModalOpen(false);
    };
    return (
      <div>
        <Image
          isZoomed
          alt="Card image"
          className="l-5 ml-2"
          src={image}
          width="150"
        />
        <Button onClick={handlePreview} color="secondary" variant="light">
          预览
        </Button>
        <Button
          onClick={handleDelete}
          color="secondary"
          variant="light"
          className="ml-3"
        >
          删除
        </Button>
        <ImagePreviewModal
          isOpen={previewIsOpen}
          onClose={handleClosePreview}
          image={image}
        />
        {/* 删除确认弹窗 */}
        <Modal
          isOpen={isDeleteModalOpen}
          onClose={handleDeleteCancel}
          size="xs"
        >
          <ModalContent>
            <ModalHeader>确认删除</ModalHeader>
            <ModalBody>确定要删除这张图片吗？</ModalBody>
            <ModalFooter>
              <Button
                onClick={handleDeleteCancel}
                color="primary"
                variant="faded"
              >
                取消
              </Button>
              <Button
                onClick={handleDeleteConfirm}
                className="ml-3"
                color="secondary"
              >
                确定
              </Button>
            </ModalFooter>
          </ModalContent>
        </Modal>
      </div>
    );
  };
  const sortedItems = React.useMemo(() => {
    return [...(items as Item[])].sort((a, b) => {
      const first = a[sortDescriptor.column as keyof Item];
      const second = b[sortDescriptor.column as keyof Item];
      const cmp = first < second ? -1 : first > second ? 1 : 0;
      return sortDescriptor.direction === "descending" ? -cmp : cmp;
    });
  }, [sortDescriptor, items]);

  const renderCell = React.useCallback((user, columnKey) => {
    const cellValue = user[columnKey];

    switch (columnKey) {
      case "title":
        return (
          <User
            avatarProps={{ radius: "full", size: "sm", src: user.avatar }}
            classNames={{
              description: "text-default-500",
            }}
            description={user.giteeUrl}
            name={cellValue}
          >
            {user.giteeUrl}
          </User>
        );
      case "content":
        return (
          <div className="flex flex-col">
            <p className="text-bold text-small capitalize">{cellValue}</p>
            <p className="text-bold text-tiny capitalize text-default-500">
              {user.team}
            </p>
          </div>
        );
      case "status":
        return (
          <Chip
            className="capitalize border-none gap-1 text-default-600"
            color={statusColorMap[user.status]}
            size="sm"
            variant="dot"
          >
            {cellValue}
          </Chip>
        );
      case "actions":
        return (
          <div className="relative flex justify-end items-center gap-2">
            <Dropdown className="bg-background border-1 border-default-100">
              <DropdownTrigger>
                <Button isIconOnly radius="full" size="sm" variant="light">
                  <VerticalDotsIcon className="text-default-200" />
                </Button>
              </DropdownTrigger>
              <DropdownMenu>
                <DropdownItem
                  onClick={() => {
                    setModaltype("edit");

                    console.log("当前航信息", user);
                    const {
                      title,
                      avatar,
                      content,
                      status,
                      images,
                      date,
                      giteeUrl,
                      id,
                    } = user;

                    onOpen();
                    setAvatar(avatar);
                    setId(id);
                    setContent(content);
                    setTitle(title);
                    setStatus(status);
                    setImages(images);
                    setGiteeUrl(giteeUrl);
                    // setSelectedDate(date);
                    // setSelectedDate(JSON.parse(date));待定研究怎么处理日期
                  }}
                >
                  {" "}
                  编辑
                </DropdownItem>
                <DropdownItem>删除</DropdownItem>
              </DropdownMenu>
            </Dropdown>
          </div>
        );
      default:
        return cellValue;
    }
  }, []);

  const onRowsPerPageChange = React.useCallback((e) => {
    setRowsPerPage(Number(e.target.value));
    setPage(1);
  }, []);

  const onSearchChange = React.useCallback((value) => {
    console.log("搜索数据", value);
    if (value) {
      setFilterValue(value);
      setPage(1);
    } else {
      setFilterValue("");
    }
  }, []);

  const topContent = React.useMemo(() => {
    return (
      <div className="flex flex-col gap-4 tablepad">
        <div className="flex justify-between gap-3 items-end">
          <Input
            isClearable
            classNames={{
              base: "w-full sm:max-w-[14%]",
              inputWrapper: "border-1",
            }}
            placeholder="搜索日志名称..."
            size="sm"
            startContent={<SearchIcon className="text-default-300" />}
            value={filterValue}
            variant="bordered"
            onClear={() => setFilterValue("")}
            onValueChange={onSearchChange}
          />
          <div className="flex gap-3 ">
            <Dropdown>
              <DropdownTrigger className="hidden sm:flex">
                <Button
                  endContent={<ChevronDownIcon className="text-small" />}
                  size="sm"
                  variant="flat"
                >
                  日志状态
                </Button>
              </DropdownTrigger>
              <DropdownMenu
                disallowEmptySelection
                aria-label="Table Columns"
                closeOnSelect={false}
                selectedKeys={statusFilter}
                selectionMode="multiple"
                onSelectionChange={setStatusFilter}
              >
                {statusOptions.map((status) => (
                  <DropdownItem key={status.uid} className="capitalize">
                    {capitalize(status.name)}
                  </DropdownItem>
                ))}
              </DropdownMenu>
            </Dropdown>
            <Dropdown>
              <DropdownTrigger className="hidden sm:flex">
                <Button
                  endContent={<ChevronDownIcon className="text-small" />}
                  size="sm"
                  variant="flat"
                >
                  可控列
                </Button>
              </DropdownTrigger>
              <DropdownMenu
                disallowEmptySelection
                aria-label="Table Columns"
                closeOnSelect={false}
                selectedKeys={visibleColumns}
                selectionMode="multiple"
                onSelectionChange={setVisibleColumns}
              >
                {columns.map((column) => (
                  <DropdownItem key={column.uid} className="capitalize">
                    {capitalize(column.name)}
                  </DropdownItem>
                ))}
              </DropdownMenu>
            </Dropdown>
            <Button
              className="bg-foreground text-background"
              endContent={<PlusIcon />}
              size="sm"
              onClick={() => {
                setModaltype("add");
                setGiteeUrl("仓库地址例如:123456@gitee.com");
                setContent("新增日志内容填写");
                setTitle("请输入日志名称！");
                setAvatar("");
                setImages([]);
                onOpen();
              }}
            >
              新增日志
            </Button>
          </div>
        </div>
        <div className="flex justify-between items-center">
          <span className="text-default-400 text-small">
            共· {initData.length} 条记录
          </span>
          <label className="flex items-center text-default-400 text-small">
            页数:
            <select
              className="bg-transparent outline-none text-default-400 text-small"
              onChange={onRowsPerPageChange}
            >
              <option value="5">5</option>
              <option value="10">10</option>
              <option value="15">15</option>
            </select>
          </label>
        </div>
      </div>
    );
  }, [
    filterValue,
    statusFilter,
    visibleColumns,
    onSearchChange,
    onRowsPerPageChange,
    initData.length,
    hasSearchFilter,
  ]);

  const bottomContent = React.useMemo(() => {
    return (
      <div className="py-2 px-2 flex justify-between items-center">
        <Pagination
          showControls
          classNames={{
            cursor: "bg-foreground text-background",
          }}
          color="default"
          isDisabled={hasSearchFilter}
          page={page}
          total={pages}
          variant="light"
          onChange={setPage}
        />
        <span className="text-small text-default-400">
          {selectedKeys === "all"
            ? "全选"
            : `${selectedKeys.size} of ${items.length} 选中`}
        </span>
      </div>
    );
  }, [selectedKeys, items.length, page, pages, hasSearchFilter]);

  const classNames = React.useMemo(
    () => ({
      wrapper: ["max-h-[382px]", "max-w-3xl"],
      th: ["bg-transparent", "text-default-500", "border-b", "border-divider"],
      td: [
        // changing the rows border radius
        // first
        "group-data-[first=true]:first:before:rounded-none",
        "group-data-[first=true]:last:before:rounded-none",
        // middle
        "group-data-[middle=true]:before:rounded-none",
        // last
        "group-data-[last=true]:first:before:rounded-none",
        "group-data-[last=true]:last:before:rounded-none",
      ],
    }),
    []
  );
  const removeImage = (imageToRemove: string) => {
    setImages(images.filter((image) => image !== imageToRemove));
  };
  return (
    <div>
      <ToastContainer
        position="top-right"
        autoClose={5000}
        hideProgressBar={false}
        newestOnTop={false}
        closeOnClick
        rtl={false}
        pauseOnFocusLoss
        draggable
        pauseOnHover
        theme="light"
      />
      <Table
        isCompact
        removeWrapper
        aria-label="Example table with custom cells, pagination and sorting "
        bottomContent={bottomContent}
        bottomContentPlacement="outside"
        checkboxesProps={{
          classNames: {
            wrapper:
              "after:bg-foreground after:text-background text-background ",
          },
        }}
        classNames={classNames}
        selectedKeys={selectedKeys}
        selectionMode="multiple"
        sortDescriptor={sortDescriptor}
        topContent={topContent}
        topContentPlacement="outside"
        onSelectionChange={setSelectedKeys}
        onSortChange={setSortDescriptor}
      >
        <TableHeader columns={headerColumns}>
          {(column) => (
            <TableColumn
              key={column.uid}
              align={column.uid === "actions" ? "center" : "start"}
              allowsSorting={column.sortable}
            >
              {column.name}
            </TableColumn>
          )}
        </TableHeader>
        <TableBody emptyContent={"没有日志可查找"} items={sortedItems}>
          {(item) => (
            <TableRow key={item.id}>
              {(columnKey) => (
                <TableCell>{renderCell(item, columnKey)}</TableCell>
              )}
            </TableRow>
          )}
        </TableBody>
      </Table>
      <Modal isOpen={isOpen} onOpenChange={onOpenChange} size={"4xl"}>
        <ModalContent>
          {(onClose) => (
            <>
              <ModalHeader className="flex flex-col gap-1">
                {modaltype === "add" ? "新增日志记录" : "编辑日志记录"}
              </ModalHeader>
              <ModalBody>
                <div className="flex items-center">
                  <Input
                    key={giteeUrlIsInvalid ? "danger" : "success"}
                    isRequired
                    labelPlacement={"outside"}
                    label={"日志名称"}
                    variant={"faded"}
                    size="sm"
                    value={title}
                    isInvalid={titleIsInvalid}
                    color={titleIsInvalid ? "danger" : "success"}
                    errorMessage={titleIsInvalid && "日志名称必填"}
                    onValueChange={setTitle}
                  />

                  <Spacer y={2} />
                  <Select
                    labelPlacement={"outside"}
                    className="ml-10"
                    color={"success"}
                    isRequired
                    label={"更新状态"}
                    size="sm"
                    placeholder="请选择更新状态"
                    defaultSelectedKeys={["paused"]}
                    selectedKeys={[status]}
                    onChange={handleStatusChange}
                  >
                    {statusList.map((item) => (
                      <SelectItem key={item.value} value={item.value}>
                        {item.label}
                      </SelectItem>
                    ))}
                  </Select>
                </div>
                <div className="flex items-center">
                  <DateInput
                    isRequired
                    labelPlacement={"outside"}
                    label={modaltype === "add" ? "新增时间" : "编辑时间"}
                    variant={"faded"}
                    size="sm"
                    granularity={"minute"}
                    color={"secondary"}
                    // isInvalid
                    // errorMessage="Please enter a valid date."
                    value={date}
                    onChange={setSelectedDate}
                  />
                  <Spacer y={2} />
                  <Input
                    labelPlacement={"outside"}
                    isRequired
                    className="ml-10"
                    color={"secondary"}
                    label="头像地址"
                    value={avatar}
                    onValueChange={setAvatar}
                    size="sm"
                  />
                </div>
                <div className="flex items-center">
                  <Input
                    key={giteeUrlIsInvalid ? "danger" : "success"}
                    isRequired
                    labelPlacement={"outside"}
                    label={"仓库地址"}
                    variant={"faded"}
                    size="sm"
                    value={giteeUrl}
                    isInvalid={giteeUrlIsInvalid}
                    color={giteeUrlIsInvalid ? "danger" : "success"}
                    errorMessage={giteeUrlIsInvalid && "仓库地址必填"}
                    onValueChange={setGiteeUrl}
                  />
                </div>
                <Textarea
                  isRequired
                  fullWidth
                  label="日志内容"
                  variant="underlined"
                  labelPlacement="outside"
                  isInvalid={contentIsInvalid}
                  color={contentIsInvalid ? "danger" : "secondary"}
                  errorMessage={contentIsInvalid && "日志内容必填"}
                  disableAnimation
                  disableAutosize
                  classNames={{
                    input: "resize-y min-h-[80px]",
                  }}
                  value={content}
                  onValueChange={setContent}
                />

                <Spacer x={2} />
                <CldUploadButton
                  uploadPreset="i8xrofhf"
                  onSuccess={(result) => {
                    console.log("响应结果", result);
                    // @ts-ignore
                    setImages((prevImages) => [...prevImages, result.info.url]);
                  }}
                >
                  <button className="bg-secondary-400 hover:bg-secondary-700 text-white font-bold py-2 px-4 rounded-lg">
                    <div className="flex">
                      <FileUp />
                      <span>
                        {" "}
                        {modaltype === "add" ? "新增上传" : "编辑上传"}
                      </span>
                    </div>
                  </button>
                </CldUploadButton>
                <Spacer x={2} />
                <div className="flex items-center">
                  {images &&
                    modaltype === "edit" &&
                    images.map((image) => (
                      <ImageComponent
                        key={image}
                        image={image}
                        images={images}
                        onRemoveImage={removeImage}
                      />
                    ))}
                </div>

                <Spacer y={2} />
              </ModalBody>
              <ModalFooter>
                <Button color="danger" variant="light" onPress={onClose}>
                  取消
                </Button>
                <Button
                  color="primary"
                  onClick={async () => {
                    console.log("图片", images);
                    const now = moment();
                    const formattedDate = now.format("YYYY-MM-DD HH:mm:ss");
                    console.log(formattedDate);
                    try {
                      const response =
                        modaltype === "add"
                          ? await axios.post(
                              process.env.API_ADDRESS + "/note",
                              {
                                userId: userId,
                                avatar,
                                content,
                                status,
                                images,
                                title,
                                date: formattedDate,
                                giteeUrl,
                              },
                              {
                                headers: {
                                  "Content-Type": "application/json",
                                },
                              }
                            )
                          : await axios.put(
                              process.env.API_ADDRESS + "/note",
                              {
                                id,
                                userId: userId,
                                avatar,
                                content,
                                status,
                                images,
                                title,
                                date: formattedDate,
                                giteeUrl,
                              },
                              {
                                headers: {
                                  "Content-Type": "application/json",
                                },
                              }
                            );
                      console.log("改为axios的响应", response);
                      if (response.data.isSucess === 1) {
                        toast.error("🦄" + response.data.message);
                        return;
                      }
                      if (
                        response.status === 200 &&
                        response.data.isSucess === 0
                      ) {
                        toast.success("🦄 发布成功");
                        fetchTicketTopics();
                      }
                      setContent("");
                      setAvatar("");
                      setImages([]);
                      onClose();
                    } catch (error) {
                      console.error("Error during API call:", error);
                      toast.error("🦄 网络异常，发布失败");
                      // 您可以添加额外的错误处理逻辑，例如显示一个错误消息给用户
                    }
                  }}
                >
                  确定
                </Button>
              </ModalFooter>
            </>
          )}
        </ModalContent>
      </Modal>
      <Space
        direction="vertical"
        align="center"
        className="mt-10 flex justify-center"
      >
        <QRCode value={text || "-"} />
      </Space>
    </div>
  );
}
